package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;;

public class Db {
    private static Db _db = null;
    
    public static Db getDb() {
        if (_db == null) {
            _db = new Db();
        }
        
        return _db;
    }
    
    public String executeQuery(String dbServerName, String database, String query, String username, String pwd) throws Exception {
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;
        String ret = "";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://" + dbServerName + "/" + database + "?" + "user=" + username + "&password=" + pwd);
            
            statement = conn.createStatement();
            rs = statement.executeQuery(query);
            ResultSetMetaData meta = rs.getMetaData();
            int colCnt = meta.getColumnCount();
            for (int i = 1; i <= colCnt; i++) {
                ret += meta.getColumnName(i) + "\t\t";
            }
            ret += "\r\n";
            
            while (rs.next()) {
                
                for (int i = 1; i <= meta.getColumnCount(); i++) {
                    ret += rs.getString(i) + "\t\t";
                }
                    
                ret += "\r\n";
            }
            return ret;
        }
        finally {
            if (rs != null) {
                rs.close();
            }
            
            if (statement != null) {
                statement.close();
            }
            
            if (conn != null) {
                conn.close();
            }
        }
    }
    
    public String executeNonQuery(String dbServerName, String database, String query, String username, String pwd) throws Exception {
        Connection conn = null;
        Statement statement = null;
        Integer ret = -1;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://" + dbServerName + "/" + database + "?" + "user=" + username + "&password=" + pwd);
            
            statement = conn.createStatement();
            ret = statement.executeUpdate(query);
            
            return ret.toString();
        }
        finally {
            if (statement != null) {
                statement.close();
            }
            
            if (conn != null) {
                conn.close();
            }
        }
    }
}
